// pages/user/applyAfterSale/applyAfterSale.js
var com = require("../../../utils/common.js");
var app = getApp();
var getImgarr = [];//需要过度展示图片
var upimgarr = [];//上传七牛云成功后返给后台的图片
var page_size = 20;
var page_index = 1;//默认页码
var submitOne = true;//限定不可多次提交
var time_id= '';//选择时间段id
var device_no="";//设备编号
var equipment_id= "";//设备id
var value_sel=[0, 0, 0];//对应数组下标
var ch_latitude= ''; //当前
var  ch_longitude= ''; //当前
Page({

  /**
   * 页面的初始数据
   */

  data: {
    go_right:'../../../images/go_right.png',
    labels: [],//服务类型
    describes: [],//问题原因
    movingShow: false,//移机地址显示
    problemShow: false,//维修问题显示
    inputData:'',//问题具体描述
    isShow: false,
    date: '', //选择日期
    time_list: [],//时间段
    start_time:'',//开始时间
    end_time: '',//结束时间
    time_index: '',
    equipmentDetail: {},//设备信息
    imgUrl: [],
    noteMaxLen: 100,
    currentNoteLen: 0, 
    add_ress: '',//详细地址
    numberPlate:'',//门牌号
    areaInfo_name: [], //选中地区名称
    area_id_Info: [], //选中的地区id信息
    remarks:'',//备注
    isTextarea: true,//弹出框textarea显隐
    searchshow: false,
    valueName: [],//设置回显选择的地址(name)
  },

  /*** 生命周期函数--监听页面加载*/
  onLoad: function (options) {
    //console.log(options)
    var that = this;
    equipment_id = options.equipment_id;
    device_no=options.device_no
    that.getEquipmentDetail();
    that.getBussinessType();
    that.getRangeTime();
    that.getReturnReason();
  },
  onShow: function(){
    submitOne = true;
    getImgarr = [];
    upimgarr = [];
  },
  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    let that=this;
    that.headid = this.selectComponent("#addre_id"); //引入地址    
  },

  // 输入门牌号
  bindNumberPlate(e){
    var that = this;
    var value = e.detail.value;
    that.setData({
      numberPlate: value
    })
    
  },
  /**
   * 选择服务类型
   */
  labelClick: function (e) {
    var that = this;
    var labels = that.data.labels;
    var index = e.currentTarget.dataset.labelindex;
    var id = e.currentTarget.dataset.business_type_id;
    // var businessTypeArr = that.data.businessTypeArr;
    var checked = labels[index].checked;
    var up = "labels["+index+"].checked";
    // 移机地址显隐
    if(id == 5){
      if (!checked){
        that.setData({
          movingShow: true,
        })
      }else{
        that.setData({
          movingShow: false,
          areaInfo_name:[],
          add_ress:''

        })
      }
    }
    // 维修问题显隐
    if (id == 6) {
      if (!checked) {
        that.setData({
          problemShow: true,
        });
      } else {
        that.setData({
          problemShow: false,
          inputData:'',
          imgUrl:[],
        });
        getImgarr=[];
        upimgarr=[];
      }
    }
    that.setData({
      [up]: !checked
    })
    // 选择移机类型后不能再选择其他的
    var isMove = false;
    for(var i in labels){
      if (labels[i].data.business_type_id == 5 && labels[i].checked){
        isMove = true;
      }
    }
    if(isMove){
      for(var i in labels){
        if (labels[i].data.business_type_id == 5){
          labels[i].checked = true;
        }else{
          labels[i].checked = false;
        }
      }
      that.setData({
        labels: labels,
        problemShow: false,
        inputData: '',
        imgUrl: [],
      })
      getImgarr = [];
      upimgarr = [];
    }
  },
  // 选择主要问题
  bindDesChange: function (e) {
    var that = this;
    var describes = that.data.describes;
    var problem_id = e.currentTarget.dataset.problem_id;
    var index = e.currentTarget.dataset.labelindex;
    var checked = describes[index].checked;
    var up = "describes[" + index + "].checked";
    that.setData({
      [up]: !checked
    })
  },
  // 绑定输入问题描述
  inputDes: function(e){
    //console.log(e.detail.value);
    var value = e.detail.value;
    var len = parseInt(value.length);
    if (len > this.data.noteMaxLen) return;

    this.setData({
      currentNoteLen: len, //当前字数 ,
      inputData: e.detail.value
    });

  },
  // 绑定输入备注
  inputRemark: function(e){
    var that = this;
    that.setData({
      remarks: e.detail.value
    })

  },
  //遮罩时阻止滚动
  myCatchTouch: function () {
    //console.log('stop user scroll it!');
    return;
  },
  // 上传图片
  uploadImages: function(){
    var that = this;
    var num = 3 - getImgarr.length;
    console.log('num:'+num);
    console.log(that.data.imgUrl);
    wx.chooseImage({
      count: num, // 默认9  
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片 
        var tempFilePaths = res.tempFilePaths
        console.log('tempFilePaths:' + tempFilePaths);
        console.log('imgUrl:' + that.data.imgUrl);
        var url = that.data.imgUrl.concat(tempFilePaths);
        for (var k = 0; k < url.length; k++) {
          that.upImg(url[k]);//循环上传图片
        }
      }
    })
  },
  //图片上传
  upImg: function (tempFilePaths) {
    var that = this;
    wx.showLoading({
      title: '上传图片中',
    })
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePaths,
      name: 'file',
      success: function (res) {
        wx.hideLoading();
        var data = JSON.parse(res.data);
        if (data.code == 1000) {
          console.log('data.data.all_url:' + data.data.all_url);
          getImgarr.push(data.data.all_url);
          upimgarr.push(data.data.url);
          that.setData({
            imgUrl: getImgarr,
          })
        } else {
          app.showToast("上传图片失败");
        }
      }
    })
  },
  //删除图片
  detailImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.detail;
    getImgarr.splice(index, 1);
    upimgarr.splice(index, 1);
    if (that.data.imgUrl.length == 0) {
      that.setData({
        imgUrl: getImgarr,
      })
    } else {
      that.setData({
        imgUrl: getImgarr,
      })
    }
  },
  //选择日期
  bindDateChange: function (e) {
    //console.log(e.detail.value);
    let that = this;
    let date = e.detail.value;
    that.setData({
      date: date
    })
  },
  //选择时间段
  bindPickerChange: function (e) {
    //console.log(e.detail.value);
    let that = this;
    let time_index = e.detail.value;
    var time_list = that.data.time_list;
    var t_id = time_list[time_index].time_id;
    that.setData({
      time_index: time_index
    })
    time_id = t_id;
  },
  //获取业务类型列表
  getBussinessType(){
    var that = this;
    app.ajax({
      url: 'Common/Common/getBussinessType',
      method: "POST",
      data: { type: 1},
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          //console.log(res.data.data);
          var labels = [];
          for(var i in res.data.data){
            labels.push({
              data: res.data.data[i],
              checked: false
            })
          }
          that.setData({
            labels: labels
          })
          console.log(labels);
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取预约时间范围
  getRangeTime() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getRangeTime',
      method: "POST",
      data: {},
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          //console.log(res.data.data);
          that.setData({
            time_list: res.data.data.time,
            start_time: res.data.data.date.start,
            end_time: res.data.data.date.end,
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取问题描述列表
  getReturnReason() {
    var that = this;
    // var business_id = that.data.business_type_id;
    console.log()
    app.ajax({
      url: 'Common/Common/getProblemList',
      method: "POST",
      data: {
        // business_id: business_id
      },
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          //console.log(res.data.data);
          var describes=[];
          for(var i in res.data.data){
            describes.push({
              data: res.data.data[i],
              checked: false
            })
          }
          that.setData({
            describes: describes
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
 
  
  //获取设备详情
  getEquipmentDetail(){
    var that = this;
    app.ajax({
      url: 'User/Equipmentlists/equipmentDetail',
      method: "POST",
      data: {
        equipment_id: equipment_id,
        device_no: device_no
      },
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          //console.log(res.data.data);
          that.setData({
            equipmentDetail: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //提交申请
  submitApply(e){
    var that = this;
    console.log('submitOne'+submitOne);
    // if (!submitOne) {
    //   console.log('多次提交');
    //   return;
    // }
    var business_type_id = that.data.business_type_id;
    var labels = that.data.labels;
    var isChecked = false;
    for(var i in labels){
      if( labels[i].checked == true){
        isChecked = true;
        break;
      }
    }
    if (!isChecked) {
      app.showToast('请选择服务类型');
      return false;
    }
    console.log('日期', that.data.date, '结果', time_id)
    if (that.data.date == '' || time_id == ''){
      app.showToast('预约日期或时间段不能为空', "none", 2000, function () { });
      return false;
    }
    for(var i in labels){
      if (labels[i].data.business_type_id == 5 && labels[i].checked){
        if (that.data.areaInfo_name.length == 0) {
          app.showToast('请选择省市区信息', "none", 2000, function () { });
          return false;
        }
        if (that.data.add_ress == '') {
          app.showToast('地址信息不能为空', "none", 2000, function () { });
          return false;
        }
        if (that.data.numberPlate == ''){
          app.showToast('详细地址不能为空',"none",2000,function(){});
          return false;
        }
      }
      if (labels[i].data.business_type_id == 6 && labels[i].checked){
        var describes = that.data.describes;
        var isChecked2 = false;
        for (var i in describes){
          if (describes[i].checked == true) {
            isChecked2 = true;
            break;
          }
        }
        if (!isChecked2) {
          app.showToast('请选择问题描述类型', "none", 2000, function () { });
          return false;
        }
        if (that.data.inputData == '') {
          app.showToast('请详细描述设备情况', "none", 2000, function () { });
          return false;
        }
        
      }
    }

    var businessTypeArr =[];
    for(var i in labels){
      if(labels[i].checked){
        businessTypeArr.push(labels[i].data.business_type_id);
      }
    }
    var des_id = [];
    for (var i in describes) {
      if (describes[i].checked == true) {
        des_id.push(describes[i].data.problem_id);
      }
    }
    submitOne = false;
//    app.saveFormId(e.detail.formId);    
    var appointment_date = that.data.date,
      appointment_time_id = time_id,
      contacts = that.data.equipmentDetail.contact,
      contact_number = that.data.equipmentDetail.contact_number,
      business_id = businessTypeArr,
      problem = that.data.inputData,
      picture = upimgarr,
      problem_key = des_id,
      move_province_code = that.data.area_id_Info[0],//移机省份—移机
      move_city_code = that.data.area_id_Info[1],//移机城市—移机
      move_area_code = that.data.area_id_Info[2],//移机区域—移机
      move_address = that.data.add_ress + '/' + that.data.numberPlate,//移机详细地址—移机
      move_lng = ch_longitude,//移机地址经度—移机
      move_lat = ch_latitude,//移机地址纬度—移机
      remarks = that.data.remarks;//备注
    app.ajax({
      url: 'User/Work/subWorkOrder',
      method: "POST",
      data: {
        appointment_date: appointment_date,
        appointment_time_id: appointment_time_id,
        contacts: contacts,
        contact_number: contact_number,
        equipment_id: equipment_id,
        business_id: business_id,
        problem: problem,
        picture: picture,
        problem_key: problem_key,
        move_province_code: move_province_code, 
        move_city_code: move_city_code,
        move_area_code: move_area_code,
        move_address: move_address,
        move_lng: move_lng,
        move_lat: move_lat, 
        remarks: remarks 
      },
      success: function (res) {
        //console.log(res)
        // that.setData({
        //   disabled: false
        // })
        if (res.data.code == 1000) {
          app.showToast(res.data.message);
          setTimeout(() => {
            wx.navigateBack({
              delta:1
            });
            submitOne = true;
          }, 1000);
        } else {
          submitOne=true;
          app.showToast(res.data.message);
        }
      }
    })
  },

  // ======================地址相关==============================================================

  //确定接受
  getSure(data) {
    console.log('确定事件获取地址', data);
    var that = this;
    that.setData({
      areaInfo_name: data.detail.areaName,
      area_id_Info: data.detail.areaId,
      valueName: data.detail.areaName
    })
  },
  //打开地图选择
  openAddress() {
    var that = this;
    this.headid.startAddressAnimation(true);
  },
  // 一下为地址(地图)选择.........................................................................................
  openaddshoose() {
    var that = this;
    wx.chooseLocation({
      success: (res) => {
        console.log('地址选择结果', res);
        ch_longitude = res.longitude;
        ch_latitude = res.latitude; 
        that.setData({
          add_ress: res.name
        })
      }
    });
  },
  //取消事件
  closefun() {
    var that = this;
    that.setData({
      pageView: false
    })
  }
})